package com.zzz.system.service;

import cn.hutool.db.meta.MetaUtil;
import com.zaxxer.hikari.HikariDataSource;
import com.zzz.codegen.entity.TableVO;
import com.zzz.framework.model.AmisSource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class TableInfoService {

    @Autowired
    private DataSourceProperties dataSourceProperties;

    @Autowired
    private DataSourceService dataSourceService;

    public DataSource getDefaultDataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(dataSourceProperties.getUrl());
        dataSource.setUsername(dataSourceProperties.getUsername());
        dataSource.setPassword(dataSourceProperties.getPassword());
        return dataSource;
    }

    /**
     * 批量获取表信息
     *
     * @param tableNames
     * @return
     */
    public List<TableVO> list(Set<String> tableNames, DataSource dataSource) {
        final DataSource ds = dataSource == null ? getDefaultDataSource() : dataSource;
        List<String> allTableNames = MetaUtil.getTables(dataSource);
        if (CollectionUtils.isEmpty(allTableNames)) {
            System.out.println("table not found.");
            return null;
        }
        List<String> filterTables = tableNames.stream().filter(allTableNames::contains).collect(Collectors.toList());
        // 按照名字排序
        return filterTables.stream().map(t -> TableVO.cp(MetaUtil.getTableMeta(ds, t))).collect(Collectors.toList());
    }

    public AmisSource listSelect(String dataSourceCode) {
        DataSource ds = dataSourceService.getDs(dataSourceCode);
        if (ds == null) {
            return new AmisSource();
        }
        List<String> tableNameList = MetaUtil.getTables(ds);
        return AmisSource.of(tableNameList, t -> t, t -> t);
    }

}
